import { emitter } from "src/util/Emitter";

type EventObj = {
  ctrlKey: boolean;
  shiftKey: boolean;
  altKey: boolean;
  key: string;
};
export class KeyboardHandler {
  globalEvents = {
    "ctrl-0": () => {
      window.$ele.electron.remote.BrowserWindow.getFocusedWindow().webContents.openDevTools();
    }
  };
  onKeyDown = (event: EventObj) => {
    const eventName = KeyboardHandler.getPreKey(event) + event.key;
    //// console.log(eventName);

    emitter.emit(eventName);
  };

  static getPreKey(event: EventObj) {
    const key = event.key;
    if (key === "Control" || key === "Shift" || key === "Alt") return "";
    let preKey = "";
    if (event.ctrlKey) {
      preKey += "ctrl-";
    }
    if (event.shiftKey) {
      preKey += "shift-";
    }
    if (event.altKey) {
      preKey += "alt-";
    }

    return preKey;
  }
  init() {
    window.addEventListener("keydown", this.onKeyDown);
    emitter.onBatch(this.globalEvents);
  }
  clear() {
    window.removeEventListener("keydown", this.onKeyDown);
    emitter.offBatch(this.globalEvents);
  }
}
